﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetCode刷题
{
    public class L0001
    {
        public static void Run()
        {
            int[] nums = new int[] { 2, 7, 11, 15 };
            int target = 9;
            var ret = TwoSum2(nums, target);
            Console.WriteLine();
        }


        public static int[] TwoSum(int[] nums, int target)
        {
            int[] result = new int[2];
            for (int i = 0; i < nums.Length; i++)
            {
                for (int j = 0; j < nums.Length; j++)
                {
                    if (j == i) continue;
                    if (nums[i] + nums[j] == target)
                    {
                        result[0] = i;
                        result[1] = j;
                        return result;
                    }

                }
            }

            return null;
        }

        public static int[] TwoSum2(int[] nums, int target)
        {
            Dictionary<int, int> kvs = new Dictionary<int, int>();
            for (int i = 0; i < nums.Length; i++)
            {
                int complement = target - nums[i];
                if (kvs.ContainsKey(complement) && kvs[complement] != i)
                {
                    return new int[] { i, kvs[complement] };
                }
                //需要对重复值进行判断,若结果包含了重复值，则已经被上面给return了；所以此处对于重复值直接忽略
                if (!kvs.ContainsKey(nums[i]))
                {
                    kvs.Add(nums[i], i);
                }
            }
            return new int[] { 0, 0 };
        }
    }
}
